package com.embhealth.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.embhealth.constant.MessageConstant;
import com.embhealth.constant.RedisMessageConstant;
import com.embhealth.entity.Result;
import com.embhealth.pojo.Member;
import com.embhealth.pojo.MemberFile;
import com.embhealth.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private MemberService memberService;

    @RequestMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map map){
        String telephone=(String)map.get("telephone");
        //进行验证码比对
        String validateCode=jedisPool.getResource().get(telephone+ RedisMessageConstant.SENDTYPE_LOGIN);
        String viewCode=(String)map.get("validateCode");
        if (viewCode!=null && viewCode.equals(validateCode)){
            //验证码校验成功
            //判断是否为会员
            Member member = memberService.findByTelephone(telephone);
            if (member==null){
                //如果查询结果空自动注册
                try{
                    member=new Member();
                    member.setRegTime(new Date());
                    member.setPhoneNumber(telephone);
                    memberService.add(member);
                    return new Result(true,"自动注册成功",member);
                }catch (Exception e){
                    e.printStackTrace();
                    return new Result(false,"会员注册失败，请重试");
                }
            }
            else {
                //向客户端预览器写入cookie
                Cookie cookie=new Cookie("member_telephone",telephone);
                cookie.setPath("/");
                cookie.setMaxAge(60*60*24*30);
                //保存cookie
                response.addCookie(cookie);
                //将会员信息保存到Redis
                String json = JSON.toJSON(member).toString();
                jedisPool.getResource().setex(telephone,60*30,json);
                return new Result(true,MessageConstant.LOGIN_SUCCESS);
            }
        }else {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }

    /**
     * 登录方法
     * @param response
     * @param request
     * @return
     */
    @RequestMapping("/logout")
    public Result login(HttpServletResponse response, HttpServletRequest request){
        try {
            Cookie[] cookies = request.getCookies();//获取cookie数组
            //遍历cookie
            String telephone="";
            for (Cookie c:cookies) {
                if (c.getName().equals("member_telephone")) {
                    telephone=c.getName();
                    Cookie cookie = new Cookie("member_telephone", null);//删除前必须要new 一个valu为空；
                    cookie.setPath("/");//路径要相同
                    cookie.setMaxAge(0);//生命周期设置为0
                    response.addCookie(cookie);
                    jedisPool.getResource().del(telephone);
                    break;
                }
            }
            return new Result(true,"退出成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"退出失败");
        }
    }

    /**
     * 会员中心的数据回显
     * @param telephone
     * @return
     */
    @RequestMapping("/findByTelephone")
    public Result findByTelephone(String telephone){
        try {
            Member member = memberService.findByTelephone(telephone);
            return new Result(true,"获取用户数据成功",member);
        }catch (Exception e){
         return new Result(false,"获取会员信息失败");
        }
    }

    /**
     * 修改用户信息
     * @param member
     * @return
     */
    @RequestMapping("edit")
    public Result edit(@RequestBody Member member){
        try {
            memberService.edit(member);
            return new Result(true,"修改信息成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"修改信息失败");
        }
    }

    /**
     * 查询档案数据
     * @return
     */
    @RequestMapping("getmemberfile")
    public Result getmemberfile(HttpServletRequest request){
        try {
            //获取用户电话
            Cookie[] cookies = request.getCookies();//获取cookie数组
            //遍历cookie
            String telephone="";
            for (Cookie c:cookies) {
                if (c.getName().equals("member_telephone")) {
                    telephone = c.getValue();
                }
            }
            MemberFile memberFile = memberService.getmemberfile(telephone);
            return new Result(true,"查询用户数据成功",memberFile);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"查询档案数据失败");
        }
    }
}
